import PateoSearchForm from '@/components/common/PateoSearchForm';
import { filterAuth } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { AddModal } from './Modal/addModal';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { ColumnsType } from 'antd/es/table';
import { debounce } from 'lodash';
import { DATE_HMS, DATE_HMS1 } from '@/support/constant/common';
import moment, { Moment } from 'moment';
import Ellipsis from '@/components/Ellipsis';
import { downloadBlobFileByURL, downloadByFetch } from '@/services/downloadURLFile';
import { getMd5, getToken } from '@/utils';
const taskTatusEnums = {
  0: '排队中',
  1: '查询中',
  2: '执行超时',
  3: '已完成',
  4: '已过期',
};
const taskTatusEnumsOpt = Object.keys(taskTatusEnums).map(key => ({
  label: taskTatusEnums[key],
  value: key,
}));
@connect((state: any) => ({
  vehicleConditionDataDownload: state.vehicleConditionDataDownload,
  loading: state.loading.effects['vehicleConditionDataDownload/postFetchPage'],
}))
export default class DataDownloads extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };
  state = {
    formValues: {
      createTimeRange: [] as any[],
      timeStart: undefined as undefined | string,
      timeEnd: undefined as undefined | string,
    },
    formData: {},
    addModalVisible: false,
    exportVisible: false,
    dataClassOpt: [],
  };
  componentDidMount() {
    const { dispatch } = this.props;
    // console.log('this.context.dicData', this.context.dicData);
    // const a = findDicByCode(this.context.dicData, 'deviceStatus');
    this.fetchPage();
    this.getDataClassOpt();
  }
  handleFormReset = () => {
    // const { dispatch } = this.props;
    const date = new Date();
    // const start = moment(date).subtract(7, 'days');
    // const end = moment(date);
    this.state.formValues = {
      createTimeRange: [],
      timeStart: undefined,
      timeEnd: undefined,
    };
    this.setState({ formValues: this.state.formValues });
  };
  closeModal = (refresh = false as string | boolean) => {
    this.setState({
      addModalVisible: false,
      exportVisible: false,
      formData: {},
    });
    if (refresh == 'edit') {
      this.handleFreshCurrentPage();
    } else if (refresh == 'add') {
      this.fetchPage();
    }
  };
  handleFreshCurrentPage = () => {
    const {
      vehicleConditionDataDownload: {
        pageData: { pagination },
      },
    } = this.props;
    this.handleTableChange(pagination);
  };
  handleTableChange = (pagination: any, filters: any = {}) => {
    const { current, pageSize } = pagination;
    const params = {
      number: current,
      size: pageSize,
      ...filters,
    };
    this.fetchPage(params);
  };
  fetchPage = (params = {}) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    // //默认7天
    // const date = new Date();
    // const start = moment(date).subtract(7, 'days');
    // const end = moment(date);
    // const initTime = {
    //   timeStart: start.format(DATE_HMS),
    //   timeEnd: end.format(DATE_HMS),
    // };
    dispatch({
      type: 'vehicleConditionDataDownload/postFetchPage',
      payload: { url: '/vehicletask/list', ...params, ...formValues },
    });
  };
  formatFormvalues = (values: any) => {
    const nweVals = { ...values };
    const createTimeRange = (values.createTimeRange ?? []).map(
      (t: any) => t.format('YYYY-MM-DD HH:mm:ss') ?? '',
    );
    nweVals.timeStart = createTimeRange[0];
    nweVals.timeEnd = createTimeRange[1];
    return nweVals;
  };
  getDataClassOpt = debounce((v = '') => {
    const { dispatch } = this.props;
    const params = {
      number: 1,
      size: 9999,
      dataClass: v,
    };
    dispatch({
      type: 'vehicleConditionDataDownload/postObjWithRes',
      payload: { url: '/dataclass/list', ...params },
      callback: res => {
        if (res.statusCode === '0') {
          this.setState({
            dataClassOpt: (res.data?.content ?? []).map(t => ({
              label: t.dataClass,
              value: t.dataClass,
            })),
          });
        } else {
          this.setState({ dataClassOpt: [] });
        }
      },
    });
  }, 100);
  render() {
    const { addModalVisible, formData, dataClassOpt, formValues } = this.state;
    const {
      vehicleConditionDataDownload: {
        pageData: { list, pagination },
      },
      loading,
      dispatch,
    } = this.props;

    const columns: ColumnsType<any> = [
      {
        title: '序号',
        dataIndex: 'rowNumber',
        width: 40,
      },

      {
        title: 'VIN码',
        dataIndex: 'vin',
        width: 150,
        ellipsis: true,
      },

      {
        title: '数据分类',
        dataIndex: 'dataClass',
        width: 150,
        ellipsis: true,
      },
      {
        title: '任务ID',
        dataIndex: 'id',
        width: 150,
        ellipsis: true,
      },
      {
        title: '下载时间范围',
        dataIndex: 'timeStart',
        width: 150,
        ellipsis: true,
        render: (v, record) => {
          return (
            <Ellipsis>
              {record.selectTimeStart}-{record.selectTimeEnd}
            </Ellipsis>
          );
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 150,
        ellipsis: true,
        render: v => v && moment(v).format(DATE_HMS),
      },
      {
        title: '任务状态',
        dataIndex: 'status',
        width: 150,
        ellipsis: true,
        render: (v: any) => taskTatusEnums[v],
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '下载文件',
              key: 'download',
              auth: 'dataDownloads-opt',
              hide: record.status !== 3,
              onConfirm: () => {
                // downloadBlobFileByURL(
                //   '/vehicletask/export',
                //   { method: 'post', data: { id: record.id, dataClass: record.dataClass } },
                //   `${record.vin}-${record.id}`
                // );
                downloadByFetch(
                  '/vehicletask/export',
                  { method: 'post', data: { id: record.id, dataClass: record.dataClass } },
                  `${record.vin}-${record.id}.csv`,
                );
              },
            },
          ];

          // btns.push(revokeBtn);
          return <PateoAuthButtons btns={btns} pathname={this.props.location.pathname} />;
        },
      },
    ];

    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const searchItems = [
      {
        type: 'input',
        title: 'VIN码',
        key: 'vin',
        placeholder: '请输入VIN',
        maxLength: 18,
      },
      {
        type: 'select',
        title: '数据分类',
        key: 'dataClass',
        placeholder: '请选择数据分类',
        options: dataClassOpt,
        showSearch: true,
        // onSearch: this.getDataClassOpt,
        optionFilterProp: 'label',
      },
      {
        type: 'select',
        title: '任务状态',
        key: 'status',
        placeholder: '任务状态',
        options: taskTatusEnumsOpt,
      },
      {
        title: '创建时间',
        type: 'rangePicker',
        key: 'createTimeRange',
        showTime: { format: DATE_HMS },
        // initialValue: formValues.createTimeRange,
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          {/* search form */}
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            handleFieldsValue={this.formatFormvalues}
            fetchParams={{
              type: 'vehicleConditionDataDownload/postFetchPage',
              url: '/vehicletask/list',
              extraArgs: {},
            }}
            dispatchFn={this.fetchPage}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            extendOffset={6}
          />
        </Card>

        <Card style={{ marginTop: 12 }} bordered={false}>
          {/* add */}
          <div>
            {filterAuth(
              'dataDownloads-opt',
              this.context.permissions,
              this.props.location.pathname,
            ) ? (
              <div className="my_newItem">
                <Button
                  icon={
                    <PlusOutlined
                      onPointerEnterCapture={undefined}
                      onPointerLeaveCapture={undefined}
                    />
                  }
                  type="primary"
                  size="small"
                  onClick={() => this.setState({ addModalVisible: true })}
                >
                  新建下载任务
                </Button>
              </div>
            ) : null}
          </div>

          {/* table */}
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'auto' }}
          />
        </Card>
        <AddModal modalVisible={addModalVisible} closeModal={this.closeModal} formData={formData} />
        {/* <ExportModal modalVisible={exportVisible} closeModal={this.closeModal} /> */}
      </div>
    );
  }
}
